<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入单据编号"></a-input>
            </a-form-model-item>

            <a-form-model-item label="采购合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入采购合同名称"></a-input>
            </a-form-model-item>

            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag type="list" v-model="model.type" dictCode="file_type" placeholder="请选择单据类型" />
            </a-form-model-item>

            <a-form-model-item label="供应商名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierId">
              <j-popup  :triggerChange="true"  @callback="popupCallback"  v-model="model.supplierName" placeholder="请输入供应商名称" code="supplier_main_info" field="supplierName" org-fields="supplier_name,id" dest-fields="supplierName,supplierId"></j-popup>
              <a-input v-model="model.supplierId" hidden />
            </a-form-model-item>

            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="4" placeholder="请输入备注" />
            </a-form-model-item>

            <a-form-model-item label="编辑合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractContent">
              <j-editor v-model="model.contractContent" />
            </a-form-model-item>
          </a-col>

          <a-col :span="18">
            <a-form-model-item label="附件" :labelCol="customLabelCol" :wrapperCol="customWrapperCol" prop="filePath">
              <j-upload v-model="model.filePath" @success="handleUploadSuccess" />
            </a-form-model-item>
            <a-card title="在线预览" v-if="model.filePath">
              <div class="pdf-container">
                <iframe :src="handlePreviewFilePDF(model.filePath)" frameborder="0" width="100%" height="100%"></iframe>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, getFileAccessHttpUrl, putAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { Base64 } from 'js-base64'
import store from '@/store'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import ActApplyBtn from '@views/flowable/components/ActApplyBtn.vue'
import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'

export default {
  name: 'BussMaterialProcurementContractReviewForm',
  components: {
    ActHistoricDetailBtn, ActApplyBtn
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data () {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      // 自定义的宽度比例，使其与第一列对齐
      customLabelCol: { span: 3 },  // 这个值需要根据实际情况调整
      customWrapperCol: { span: 21 }, // 这个值需要根据实际情况调整
      model: {
        code: "",
        name: "",
        type: "",
        supplierId: "",
        remark: "",
        contractContent: "",
        filePath: ""
      },
      // 添加一个默认空数组
      customFormData: [],
      confirmLoading: false,
      validatorRules: {
        name: [
          { required: true, message: '请输入单据名称!'},
        ],
      },
      url: {
        add: "/procurement/bussMaterialProcurementContractReview/add",
        edit: "/procurement/bussMaterialProcurementContractReview/edit",
        queryById: "/procurement/bussMaterialProcurementContractReview/queryById"
      }
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
  created () {
    console.log("----------this.customFormData=", this.customFormData);

    if (this.customFormData && this.customFormData.length > 0 && this.customFormData[0].id) {
      this.model = this.customFormData[0];
      console.log("this.customFormData=", this.customFormData);
      this.$forceUpdate();
    } else {
      console.warn("customFormData 为空或未定义，初始化为默认值");
      // 这里可以根据需求设置默认 model 值
    }

    // 备份 model 原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    popupCallback(res){
      this.model.supplierName = res.supplierName
      this.model.supplierId   = res.supplierId
      console.log('回调里拿到 id', res.supplierId) // 调试用
    },
    handleLog(){
      console.log("11111111",this.model)
    },
    handleUploadSuccess(file) {
      // 处理文件上传成功
      const reader = new FileReader();
      reader.onload = (event) => {
        const arrayBuffer = event.target.result;
        mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
          .then((result) => {
            this.model.contractContent = result.value;
          })
          .catch((err) => {
            console.error("解析Word文档失败:", err);
          });
      };
      reader.readAsArrayBuffer(file.raw);
    },
    handlePreviewFilePDF(rowpath) {
      let realPath = this.getImgView(rowpath)
      let base = window._CONFIG.onlinePreviewDomainURL + '/onlinePreview?url='
      let codename = Base64.encode(realPath)
      let url = base + codename + '&watermarkTxt=' + encodeURIComponent(store.getters.userInfo.username)
      return url
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    submitForm () {
      console.log("2123",this.model)
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
            method = 'put';
          }
          httpAction(httpurl,this.model,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },

    getSequenceNum() {
      let url = "/sys/fillRule/executeRuleByCode/procurement_review_code";
      putAction(url, {}).then(res => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result;
        }
      })
    },

    add () {
      this.edit(this.modelDefault);
      this.getSequenceNum()
    },
    edit (record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
  }
}
</script>

<style scoped>
/* 确保全宽字段占满整行宽度 */
.full-width-fields {
  width: 100%;
}

/* 可能需要覆盖一些默认样式 */
/deep/ .full-width-fields .ant-form-item-control-wrapper {
  width: 100%;
}

/* 如果需要，调整左侧标签的对齐方式 */
/deep/ .full-width-fields .ant-form-item-label {
  text-align: left;
}

/* 附件查看的容器样式 */
.pdf-container {
  width: 100%;          /* 确保容器宽度填满 */
  height: 500px;       /* 设置固定高度，以便在内容溢出时显示滚动条 */
  overflow: auto;      /* 当内容超出容器高度时显示滚动条 */
  border: 1px solid #ccc; /* 为容器添加边框以更好地展示 */
}
</style>